package com.xmall.service.impl;

import com.xmall.bean.bo.CheckList;
import com.xmall.bean.table.*;

import com.xmall.bean.vo.BaseRespVo;
import com.xmall.bean.vo.CartTotalBean;
import com.xmall.bean.vo.CartVo;
import com.xmall.mapper.*;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import com.xmall.bean.vo.CheckoutCartVo;
import com.xmall.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import com.xmall.mapper.AddressMapper;
import com.xmall.mapper.CartMapper;
import com.xmall.mapper.CouponMapper;
import com.xmall.mapper.SystemMapper;
import com.xmall.service.CartServcie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.System;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements CartServcie {

    @Autowired
    SystemMapper systemMapper;
    @Autowired
    CartMapper cartMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired

    GoodsMapper goodsMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Autowired
    GrouponRulesMapper grouponRulesMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Override
    public CartVo indexCart() {

        CartVo cartVo = new CartVo();
        CartTotalBean cartTotalBean = new CartTotalBean();

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false);

        List<Cart> carts = cartMapper.selectByExample(cartExample);
        cartVo.setCartList(carts);

        criteria.andCheckedEqualTo(true);
        List<Cart> cartsChecked = cartMapper.selectByExample(cartExample);
        BigDecimal sumPriC = new BigDecimal(0);
        Integer sumNum = 0;
        if (cartsChecked.size() != 0) {
            for (Cart cart : cartsChecked) {

                Short number = cart.getNumber();
                BigDecimal price = cart.getPrice();

                BigDecimal multiply = price.multiply(BigDecimal.valueOf(Long.parseLong(number.toString())));

                sumPriC = sumPriC.add(multiply);

                sumNum += number;
            }
        }
        cartTotalBean.setGoodsCount(sumNum.shortValue());
        cartTotalBean.setGoodsAmount(sumPriC);

        short sum = 0;
        BigDecimal sumPri = new BigDecimal(0);


        criteria.andCheckedEqualTo(true);
        List<Cart> carts1 = cartMapper.selectByExample(cartExample);
        for (Cart cart : carts1) {
            cart.setAddTime(new Date());
            cart.setUpdateTime(new Date());
            Sumall sumall = new Sumall(cartTotalBean, sum, sumPri, cart).invoke();
            sum = sumall.getSum();
            sumPri = sumall.getSumPri();
        }


        BigDecimal bigDecimal = BigDecimal.valueOf(Long.parseLong("0"));
        Short s = 0;
        cartTotalBean.setGoodsCount(s);
        cartTotalBean.setGoodsAmount(bigDecimal);
        cartTotalBean.setCheckedGoodsAmount(bigDecimal);
        cartTotalBean.setCheckedGoodsCount(s);

        cartTotalBean.setCheckedGoodsAmount(sumPriC);
        cartTotalBean.setCheckedGoodsCount(sumNum.shortValue());

        cartVo.setCartTotal(cartTotalBean);
        return cartVo;
    }

    @Override
    public void updateCart(Cart cart) {
        System.out.println(cart.getNumber());
        Short number = cart.getNumber();
        Integer id = cart.getId();
        cartMapper.updateCart(id, number.intValue());


    }

    @Override
    public CartVo checkCart(CheckList checkList) {
        Integer isChecked = checkList.getIsChecked();
        Integer[] productIds = checkList.getProductIds();

        boolean checked = false;
        checked = !checked;
        //1 为true，选中状态
        if (isChecked == 0) {

            //checked true --> false
            changeChecked(productIds, true, false);

        } else if (isChecked == 1) {
            //checked false --> true
            changeChecked(productIds, false, true);
        }

        CartVo cartVo = new CartVo();
        CartTotalBean cartTotalBean = new CartTotalBean();


        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();

        criteria.andDeletedEqualTo(false);

        List<Cart> carts = cartMapper.selectByExample(cartExample);
        cartVo.setCartList(carts);

        short sum = 0;
        BigDecimal sumPri = new BigDecimal(0);
        criteria.andCheckedEqualTo(true);
        List<Cart> carts2 = cartMapper.selectByExample(cartExample);

        if (carts2.size() != 0) {
            for (Cart cart : carts2) {
                Sumall sumall = new Sumall(cartTotalBean, sum, sumPri, cart).invoke();
                sum = sumall.getSum();
                sumPri = sumall.getSumPri();
            }
        }


        BigDecimal bigDecimal = BigDecimal.valueOf(Long.parseLong("0"));
        Short s = 0;

        if (carts2.size() == 0) {
            cartTotalBean.setGoodsCount(s);
            cartTotalBean.setGoodsAmount(bigDecimal);
            cartTotalBean.setCheckedGoodsAmount(bigDecimal);
            cartTotalBean.setCheckedGoodsCount(s);
        }


        cartVo.setCartTotal(cartTotalBean);

        return cartVo;
    }

    private void changeChecked(Integer[] productIds, boolean b, boolean b2) {
        for (Integer productId : productIds) {
            CartExample cartExampleTrue = new CartExample();
            CartExample.Criteria criteriaTrue = cartExampleTrue.createCriteria();
            criteriaTrue.andCheckedEqualTo(b);
            Cart cartTrue = new Cart();
            cartTrue.setChecked(b2);
            criteriaTrue.andProductIdEqualTo(productId);
            cartMapper.updateByExampleSelective(cartTrue, cartExampleTrue);
        }
    }

    @Override
    public CartVo delete(CheckList checkList) {

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        Integer[] productIds = checkList.getProductIds();
        List<Integer> integers = new ArrayList<>();
        for (Integer productId : productIds) {
            integers.add(productId);
        }
        Cart cart = new Cart();
        cart.setDeleted(true);
        criteria.andProductIdIn(integers);
        cartMapper.updateByExampleSelective(cart, cartExample);
        return null;
    }

    @Override
    public Integer goodscount() {

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andCheckedEqualTo(true);
        List<Cart> carts = cartMapper.selectByExample(cartExample);

        int sum = 0;
        for (Cart cart : carts) {
            Short number = cart.getNumber();
            sum += number;
        }

        return sum;
    }

    @Override
    public Integer add(Cart cart) {


        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer userId = user.getId();

        Integer productId = cart.getProductId();
        Short number = cart.getNumber();
        Integer goodsId = cart.getGoodsId();

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteriaCart = cartExample.createCriteria();
        criteriaCart.andUserIdEqualTo(userId);
        criteriaCart.andGoodsIdEqualTo(goodsId);
        criteriaCart.andProductIdEqualTo(productId);

        CartExample cartExampleSelect = new CartExample();
        CartExample.Criteria criteriaSelect = cartExampleSelect.createCriteria();
        criteriaSelect.andCheckedEqualTo(true);
        criteriaSelect.andDeletedEqualTo(false);

        List<Cart> cartsSelect = cartMapper.selectByExample(cartExampleSelect);
        Integer sum = 0;
        for (Cart cart1 : cartsSelect) {
            Short number1 = cart1.getNumber();
            sum += number1;
        }

        int numAll = number + sum;
        short numTotal = (short) numAll;
        List<Cart> carts = cartMapper.selectByExample(cartExample);

//获取product表中的规格，价格，
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria criteriaProduct = goodsProductExample.createCriteria();
        criteriaProduct.andIdEqualTo(productId);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        GoodsProduct goodsProduct = goodsProducts.get(0);

        Cart cartAdd = new Cart();
        //获取goods表中的数据
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteriaGoods = goodsExample.createCriteria();
        criteriaGoods.andIdEqualTo(goodsId);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);
        Goods goodsAdd = goods.get(0);


        CartExample cartExampleUpdate = new CartExample();
        CartExample.Criteria criteriaUpdate = cartExampleUpdate.createCriteria();
        Cart cartUpdate = new Cart();
        criteriaUpdate.andUserIdEqualTo(userId);
        criteriaCart.andGoodsIdEqualTo(goodsId);
        criteriaUpdate.andProductIdEqualTo(productId);

        if (carts != null && carts.size() != 0) {
            //TODO 和购物车的number相加
            Cart cart1 = carts.get(0);
            Short number1 = cart1.getNumber();
            int numUpdate = number + number1;
            short numUp = (short) numUpdate;
            cartUpdate.setNumber(numUp);
            cartMapper.updateByExampleSelective(cartUpdate, cartExample);
        } else {
            cartAdd.setUserId(userId);
            cartAdd.setGoodsId(goodsId);
            cartAdd.setGoodsSn(goodsId.toString());
            cartAdd.setGoodsName(goodsAdd.getName());
            cartAdd.setProductId(productId);
            cartAdd.setPrice(goodsProduct.getPrice());
            cartAdd.setNumber(number);
            cartAdd.setSpecifications(goodsProduct.getSpecifications());
            cartAdd.setChecked(true);
            cartAdd.setPicUrl(goodsAdd.getPicUrl());
            cartAdd.setAddTime(new Date());
            cartAdd.setUpdateTime(new Date());
            cartAdd.setDeleted(false);
            cartMapper.insert(cartAdd);

        }

        return numAll;
    }

    @Override
    public Integer fastadd(Cart cart) {

        Subject subject = SecurityUtils.getSubject();
        User principal = (User) subject.getPrincipal();
        Integer userId = principal.getId();
        add(cart);

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andProductIdEqualTo(cart.getProductId());
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        Cart cart1 = carts.get(0);
        Integer id = cart1.getId();
        return id;

    }

    @Override
    public CheckoutCartVo checkoutCart(Integer cartId, Integer addressId, Integer couponId, Integer grouponRulesId) {

        // 获取团购价格
        BigDecimal grouponPrice = new BigDecimal(0);
        if (grouponRulesId != 0) {
            GrouponRules grouponRules = grouponRulesMapper.selectByPrimaryKey(grouponRulesId);
            grouponPrice = grouponRules.getDiscount();
        }
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer userId = user.getId();
        // 获取实际价格
        // TODO: 2020/12/11  cartId 如果为0，则是购物车下单，选择checked 为1 以及delete 为 0 的 以及对应的userId
        Cart cart = cartMapper.selectByPrimaryKey(cartId);
        BigDecimal actualPrice = cart.getPrice();
        // 获取商品合计价格
        actualPrice = actualPrice.multiply(new BigDecimal(cart.getNumber()));
        BigDecimal goodsTotalPrice = actualPrice;
        // 获取地址信息
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andIsDefaultEqualTo(true);
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        Address checkedAddress = addresses.get(0);
        // 获取优惠价格
        BigDecimal couponPrice = new BigDecimal(0);
        if (couponId != -1 && couponId != 0) {
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
            couponPrice = coupon.getDiscount();
        }
        // 获取可用优惠券数目
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria couponUserExampleCriteria = couponUserExample.createCriteria();
        couponUserExampleCriteria.andUserIdEqualTo(userId).andDeletedEqualTo(false);
        int availableCouponLength = (int) couponUserMapper.countByExample(couponUserExample);
        // 获取邮费
        BigDecimal freigthPrice = new BigDecimal(0);
        SystemExample systemExample = new SystemExample();
        SystemExample.Criteria systemExampleCriteria = systemExample.createCriteria();
        systemExampleCriteria.andKeyNameEqualTo("cskaoyan_mall_express_freight_min").andDeletedEqualTo(false);
        List<com.xmall.bean.table.System> systems = systemMapper.selectByExample(systemExample);
        int minPrice = Integer.parseInt(systems.get(0).getKeyValue());
        if (actualPrice.intValue() < minPrice) {
            SystemExample systemExample1 = new SystemExample();
            SystemExample.Criteria systemExample1Criteria = systemExample1.createCriteria();
            systemExample1Criteria.andKeyNameEqualTo("cskaoyan_mall_express_freight_value").andDeletedEqualTo(false);
            List<com.xmall.bean.table.System> systems1 = systemMapper.selectByExample(systemExample1);
            freigthPrice = new BigDecimal(systems1.get(0).getKeyValue());
        }

        // 获取订单总价格
        BigDecimal orderTotalPrice = actualPrice.subtract(couponPrice).add(freigthPrice);
        // 获取购物车已勾选商品列表
        CartExample cartExample = new CartExample();
        CartExample.Criteria cartExampleCriteria = cartExample.createCriteria();
        cartExampleCriteria.andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        List<Cart> checkedGoodsList = cartMapper.selectByExample(cartExample);
        CheckoutCartVo cartCheckoutVo = new CheckoutCartVo(grouponPrice, grouponRulesId, checkedAddress, actualPrice,
                orderTotalPrice, couponPrice, availableCouponLength, couponId, freigthPrice, goodsTotalPrice, addressId, checkedGoodsList);
        return cartCheckoutVo;

    }

    private Integer getSystemValue(String keyname) {
        SystemExample example = new SystemExample();
        example.createCriteria().andKeyNameEqualTo(keyname);
        List<com.xmall.bean.table.System> valueList = systemMapper.selectByExample(example);
        return Integer.parseInt(valueList.get(0).getKeyValue());
    }


    private class Sumall {
        private CartTotalBean cartTotalBean;
        private short sum;
        private BigDecimal sumPri;
        private Cart cart;


        public Sumall(CartTotalBean cartTotalBean, short sum, BigDecimal sumPri, Cart cart) {
            this.cartTotalBean = cartTotalBean;
            this.sum = sum;
            this.sumPri = sumPri;
            this.cart = cart;
        }

        public short getSum() {
            return sum;
        }

        public BigDecimal getSumPri() {
            return sumPri;
        }

        public Sumall invoke() {

            Short number = cart.getNumber();
            BigDecimal price = cart.getPrice();

            sum += (short) (number);
            cartTotalBean.setGoodsCount(sum);
            cartTotalBean.setCheckedGoodsCount(sum);
            BigDecimal bigDecimal = BigDecimal.valueOf(((Short) number).longValue()).multiply(price);
            sumPri = sumPri.add(bigDecimal);
            cartTotalBean.setGoodsAmount(sumPri);
            cartTotalBean.setCheckedGoodsAmount(sumPri);
            return this;
        }
    }
}

